package com.meiyu.live.ui.main;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseFragment;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.param.MeiyuListParams;
import com.meiyu.live.net.response.HotLiveResponse;
import com.meiyu.live.popj.LiveRoom;
import com.meiyu.live.tv.audience.AudienceActivity;
import com.meiyu.live.util.BitmapHelp;
import com.meiyu.live.widget.NetLoadingDailog;

/**
 * 热门
 */
public class HotliveFragment extends BaseFragment {


    protected NetLoadingDailog dialog_loading;
//    private MSGView msgView;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private DataListAdapter adapter;
    //    private View footerView;
    private DrawerLayout drawerLayout;
    private static final int PAGE_SIZE = 10;
    private int index = 1;
    private boolean hasMore = true;
    private HotLiveResponse hotLiveResponse = new HotLiveResponse();
    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    RecyclerView.LayoutManager layoutManager;
    int type;

    public HotliveFragment() {
    }

    public static HotliveFragment newInstance(int type) {
        HotliveFragment fragment = new HotliveFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type",type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getContextView() {
        return R.layout.fragment_allhotlive;
    }

    @Override
    protected void init() {
        type = getArguments().getInt("type");
        inflater = LayoutInflater.from(getContext());
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        dialog_loading = new NetLoadingDailog(getContext());
//        msgView = (MSGView) findViewById(R.id.msgView);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new DataListAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 判断滚动到底部
                if (isSlideToBottom(recyclerView) && hasMore) {
                    getData(false);
                }
            }

            protected boolean isSlideToBottom(RecyclerView recyclerView) {
                if (recyclerView == null) return false;
                if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
                    return true;
                return false;
            }
        });

        dialog_loading.loading();
        getData(true);
    }

    private void getData(final boolean reload) {
        if (reload) {
            index = 1;
            hasMore = true;
        }
        int area[] = {PAGE_SIZE, index * PAGE_SIZE};
        MeiyuListParams pageParams = new MeiyuListParams(type, area);
        pageParams.setUrl(Constant.UrlParams.MEIYU_LIST);
        request(pageParams, HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse indexAllResponse) {
                dialog_loading.dismissDialog();
                refreshLayout.setRefreshing(false);
                if (indexAllResponse != null) {
                    if (reload) {
                        hotLiveResponse.getHash().clear();
                    }
                    hotLiveResponse.getHash().addAll(indexAllResponse.getHash());
                    index += 1;
                    if (indexAllResponse.getHash().size() < PAGE_SIZE) {
                        hasMore = false;
                    }
                    adapter.notifyDataSetChanged();
                    if (hotLiveResponse.getHash().size() == 0) {
//                        msgView.show_empty();
                    } else {
//                        msgView.dismiss();
                    }
                } else {
//                    msgView.show_error();
                }

            }
        });
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        dialog_loading.dismissDialog();
        refreshLayout.setRefreshing(false);
        super.onErrorResponse(volleyError);
    }

    class DataListAdapter extends RecyclerView.Adapter<DataListAdapter.ViewHolder> {

        @Override
        public DataListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            int res = R.layout.adapter_nowlive_item1;

            View view = inflater.inflate(res, parent, false);
            return new DataListAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(DataListAdapter.ViewHolder holder, int position) {
            holder.layout_root.setTag(position);
            final LiveRoom bean = hotLiveResponse.getHash().get(position);
            imageLoader.displayImage(BitmapHelp.getImgByCdn(bean.getAvatar(), "m_fill", "400", "600"), holder.iv_avatar, options);
            holder.tv_name.setText(bean.getAnchor_name());
            holder.tv_content.setText(TextUtils.isEmpty(bean.getDescription()) ? "无介绍" : bean.getDescription());
            holder.tv_appoint.setText(bean.getViewer_num() + "人正在观看");
        }

        @Override
        public int getItemCount() {
            return hotLiveResponse != null && hotLiveResponse.getHash() != null ? hotLiveResponse.getHash().size() : 0;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public View layout_root;
            public TextView tv_name, tv_content, tv_appoint;
            public ImageView iv_avatar;

            public ViewHolder(View itemView) {
                super(itemView);
                layout_root = itemView.findViewById(R.id.layout_root);
                layout_root.setOnClickListener(onItemClickListener);
                tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                iv_avatar = (ImageView) itemView.findViewById(R.id.iv_avatar);
                tv_content = (TextView) itemView.findViewById(R.id.tv_content);
                tv_appoint = (TextView) itemView.findViewById(R.id.tv_appoint);
            }
        }

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final LiveRoom bean = hotLiveResponse.getHash().get(index);
                AudienceActivity.start(getActivity(), bean);
            }
        };
    }


}
